package org.breathe.thread.pool.common.queue;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 计算用于使用当前最大可用内存的百分比来限制内存
 * 简化了原先实现
 * 借鉴了apache
 * @author: breathe
 * @createTime: 2025-04-09
 */
public class MemoryLimitCalculator {
    private static volatile long maxAvailable;
    private static final ScheduledExecutorService SCHEDULER = Executors.newSingleThreadScheduledExecutor();

    static {
        refresh();
        SCHEDULER.scheduleWithFixedDelay(MemoryLimitCalculator::refresh, 50, 50, TimeUnit.MILLISECONDS);
        Runtime.getRuntime().addShutdownHook(new Thread(SCHEDULER::shutdown));
    }
    private static void refresh() {
        maxAvailable = Runtime.getRuntime().freeMemory();
    }

    public static long maxAvailable() {
        return maxAvailable;
    }
}
